<template>
  <view class="user-page">
    <up-navbar title="" :bgColor="bgColor" height="50" fixed placeholder>
      <template #left>
        <text>书法展览</text>
      </template>
    </up-navbar>
    <view class="content">
      <!-- 顶部用户信息卡片 -->
      <view class="user-card">
        <view class="user-info">
          <image class="avatar" :src="userInfo.avatar" mode="aspectFill" @click.stop="handleAvatarClick" />
          <view class="info-right">
            <view class="name">{{ userInfo.isGuest ? '游客用户' : (userInfo.isLoggedIn ? userInfo.nickname : '点击头像登录') }}
            </view>
            <view class="member-tag">
              <uni-icons type="vip" size="14" color="#FFD700"></uni-icons>
              <text>{{ userInfo.isGuest ? '游客模式' : (userInfo.isLoggedIn ? '普通会员' : '未登录') }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 我的功能卡片 -->
      <view class="section-card">
        <view class="my-features-grid">
          <view class="feature-item" v-for="(item, index) in myFeatures" :key="index" @click="navigateTo(item.path)">
            <view class="feature-icon">
              <uni-icons :type="item.icon" size="24" :color="item.color"></uni-icons>
            </view>
            <view class="feature-content">
              <text class="feature-name">{{ item.name }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 常用功能 -->
      <view class="section-card">
        <view class="feature-list">
          <view class="feature-item" v-for="(item, index) in menuItems" :key="index" @click="navigateTo(item)">
            <view class="feature-icon">
              <uni-icons :type="item.icon" size="20" color="#666"></uni-icons>
            </view>
            <view class="feature-content">
              <text class="feature-name">{{ item.name }}</text>
            </view>
            <view class="feature-arrow">
              <text v-if="item.name === '检查更新'" class="app-version">{{ appVersion }}</text>
              <text v-else-if="item.count" class="cache-size">{{ item.count }}</text>
              <!-- <text v-if="item.name === '清除缓存'" class="cache-size">{{ cacheSize }}</text> -->
              <uni-icons type="right" size="16" color="#ccc"></uni-icons>

            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 悬浮AI助手按钮 -->
    <floating-ai-btn :bottomOffset="100" :showTip="false" @click="handleAiBtnClick">
    </floating-ai-btn>
  </view>
</template>

<script setup>
import { reactive, onMounted, ref } from 'vue'
import FloatingAiBtn from '@/components/floating-ai-btn/floating-ai-btn.vue'
import { initTestData } from '@/utils/initData.js'

const cacheSize = ref('12.5MB')
const appVersion = ref('1.0.0') // 默认版本号

const userInfo = reactive({
  avatar: '', // 使用logo作为默认头像
  nickname: '',
  phone: '',
  isLoggedIn: false, // 登录状态
  isGuest: false // 是否为游客模式
})

// 我的功能数据
const myFeatures = reactive([
  {
    name: '我的收藏',
    icon: 'star',
    color: '#ff6b35',
    path: '/pages/collection/list',
    count: '12'
  },
  {
    name: '我的点赞',
    icon: 'heart',
    color: '#e91e63',
    path: '/pages/like/list',
    count: '24'
  },
  {
    name: '我的评价',
    icon: 'chat',
    color: '#2196f3',
    path: '/pages/review/list',
    count: '8'
  }
])

const menuItems = reactive([
  { name: '收货地址', icon: 'location', path: '/pages/user/address/list' },
  { name: '联系客服', icon: 'headphones', path: '/pages/user/service/index' },
  { name: '检查更新', icon: 'reload', path: '', handler: 'checkForUpdate' }, // 添加检查更新功能
  // { name: '清除缓存', icon: 'trash', path: '', handler: 'clearCache' }, // 添加清除缓存功能
  { name: '关于我们', icon: 'info-circle', path: '/pages/user/about/index' }
])

// 获取地址数量
const getAddressCount = () => {
  try {
    const addresses = uni.getStorageSync('userAddresses') || []
    return addresses.length
  } catch (error) {
    console.error('获取地址数量失败:', error)
    return 0
  }
}

// 在menuItems中添加地址数量显示
const updateMenuItems = () => {
  const addressItem = menuItems.find(item => item.name === '收货地址')
  if (addressItem) {
    const count = getAddressCount()
    addressItem.count = count > 0 ? `${count}` : ''
  }
}

const getUserInfo = () => {
  // 获取用户信息
  const storedUserInfo = uni.getStorageSync('userInfo')
  if (storedUserInfo) {
    Object.assign(userInfo, JSON.parse(storedUserInfo))
  }
}

const navigateTo = (item) => {
  // 如果有自定义处理程序，调用它
  if (item.handler) {
    switch (item.handler) {
      case 'checkForUpdate':
        checkForUpdate()
        break
      case 'clearCache':
        clearCache()
        break
      default:
        uni.showToast({
          title: '功能开发中',
          icon: 'none'
        })
    }
    return
  }

  // 否则使用路径导航
  if (item.path) {
    uni.navigateTo({
      url: item.path,
      fail: () => {
        uni.showToast({
          title: '页面开发中',
          icon: 'none'
        })
      }
    })
  }
}

// 处理AI按钮点击
const handleAiBtnClick = () => {
  console.log('用户页AI按钮点击')
}

// 处理头像点击 - 根据登录状态执行不同操作
const handleAvatarClick = () => {
  // 检查是否已登录
  if (!userInfo.isLoggedIn || userInfo.isGuest) {
    // 未登录或游客模式，显示提示框
    uni.showModal({
      title: '提示',
      content: '您尚未登录，是否前往登录？',
      confirmText: '去登录',
      cancelText: '取消',
      success: (res) => {
        if (res.confirm) {
          // 用户点击去登录，跳转到登录页面
          uni.navigateTo({
            url: '/pages/login/index',
            success: () => {
              console.log('跳转到登录页面成功')
            },
            fail: (err) => {
              console.error('跳转登录页面失败:', err)
              uni.showToast({
                title: '页面跳转失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
    return
  }

  // 已登录用户，跳转到个人信息页面
  uni.navigateTo({
    url: '/pages/user/profile',
    success: () => {
      console.log('跳转到个人信息页面成功')
    },
    fail: (err) => {
      console.error('跳转个人信息页面失败:', err)
      uni.showToast({
        title: '页面跳转失败',
        icon: 'none'
      })
    }
  })
}

// 清除缓存
const clearCache = () => {
  uni.showModal({
    title: '提示',
    content: '确定要清除缓存吗？',
    success: (res) => {
      if (res.confirm) {
        try {
          // 清除所有本地存储数据
          uni.clearStorageSync()

          // 重新设置必要的数据
          cacheSize.value = '0MB'

          // 重新加载用户信息（因为用户信息也被清除了）
          getUserInfo()

          uni.showToast({
            title: '缓存清除成功',
            icon: 'success'
          })
        } catch (error) {
          console.error('清除缓存失败', error)
          uni.showToast({
            title: '清除缓存失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 检查更新
const checkForUpdate = () => {
  // #ifdef MP-WEIXIN
  // 调用全局的检查更新方法
  if (typeof uni.checkForUpdate === 'function') {
    uni.checkForUpdate()
  } else {
    uni.showToast({
      title: '检查更新功能暂不可用',
      icon: 'none'
    })
  }
  // #endif

  // #ifndef MP-WEIXIN
  uni.showToast({
    title: '仅支持微信小程序更新',
    icon: 'none'
  })
  // #endif
}

// 获取应用版本号
const getAppVersion = () => {
  // #ifdef MP-WEIXIN
  const accountInfo = uni.getAccountInfoSync()
  if (accountInfo && accountInfo.miniProgram && accountInfo.miniProgram.version) {
    appVersion.value = accountInfo.miniProgram.version
  }
  // #endif
}

// 页面显示时获取用户信息
onMounted(() => {
  initTestData()
  getUserInfo()
  getAppVersion()
  updateMenuItems()
})

// 使用选项API处理页面显示（从登录页面返回时刷新）
defineExpose({
  onShow() {
    getUserInfo()
    updateMenuItems()
  }
})
</script>

<style lang="scss" scoped>
.user-page {
  min-height: 100vh;
  background-color: #f8f8f8;

}

.content {
  padding: 10rpx 10rpx 36rpx;
}

.user-card {
  background: linear-gradient(135deg, #ff0101, #fc7304);
  border-radius: 20rpx;
  padding: 60rpx 40rpx;
  color: #fff;
  min-height: 200rpx;

  .user-info {
    display: flex;
    align-items: center;

    .avatar {
      width: 130rpx;
      height: 130rpx;
      border-radius: 50%;
      border: 4rpx solid rgba(255, 255, 255, 0.3);
    }

    .info-right {
      flex: 1;
      margin-left: 30rpx;

      .name {
        font-size: 40rpx;
        font-weight: 600;
        margin-bottom: 16rpx;
      }

      .member-tag {
        display: flex;
        align-items: center;
        background: rgba(255, 255, 255, 0.2);
        padding: 4rpx 16rpx;
        border-radius: 24rpx;
        width: fit-content;

        text {
          font-size: 24rpx;
          margin-left: 8rpx;
        }
      }
    }
  }
}

.section-card {
  background-color: #fff;
  border-radius: 24rpx;
  margin-top: 30rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.04);

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;

    .section-title {
      display: flex;
      align-items: center;
      gap: 12rpx;

      text {
        font-size: 32rpx;
        font-weight: 600;
        color: #333;
      }
    }

    .more {
      display: flex;
      align-items: center;
      color: #999;
      font-size: 26rpx;
    }
  }
}

// 我的功能网格样式
.my-features-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16rpx;

  .feature-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx 16rpx;
    background: #f8f9fa;
    border-radius: 12rpx;
    transition: all 0.3s ease;
    text-align: center;

    &:active {
      background: #e9ecef;
      transform: scale(0.95);
    }

    .feature-icon {
      width: 48rpx;
      height: 48rpx;
      background: #fff;
      border-radius: 12rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 10rpx;
      box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.05);
    }

    .feature-content {
      margin-bottom: 8rpx;

      .feature-name {
        display: block;
        font-size: 22rpx;
        font-weight: 500;
        color: #333;
        margin-bottom: 4rpx;
      }

      .feature-desc {
        display: block;
        font-size: 18rpx;
        color: #999;
        line-height: 1.3;
      }
    }

    .feature-count {
      font-size: 24rpx;
      font-weight: 600;
      color: #ff6b35;
    }
  }
}

.grid-menu {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 30rpx;

  .grid-item {
    text-align: center;

    .icon-box {
      width: 90rpx;
      height: 90rpx;
      margin: 0 auto 0;
      background: #f7f7f7;
      border-radius: 24rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    text {
      font-size: 26rpx;
      color: #333;
    }
  }
}

// 常用功能列表样式
.feature-list {
  display: flex;
  flex-direction: column;

  .feature-item {
    display: flex;
    align-items: center;
    padding: 24rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
    transition: all 0.3s ease;

    &:last-child {
      border-bottom: none;
    }

    &:active {
      background: #f8f9fa;
      transform: scale(0.98);
    }

    .feature-icon {
      width: 60rpx;
      height: 60rpx;
      background: #f8f9fa;
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 24rpx;
      flex-shrink: 0;
    }

    .feature-content {
      flex: 1;

      .feature-name {
        font-size: 30rpx;
        font-weight: 500;
        color: #333;
      }
    }

    .feature-arrow {
      margin-left: 16rpx;
      flex-shrink: 0;
    }

    .app-version {
      color: #999;
    }

    .cache-size {
      color: #409eff;
    }
  }
}
</style>